<template>
<div class="todo-checkbox">
  <el-checkbox-group v-model="checkList">
      <el-checkbox  v-for="(item,index) in todos" :key="index"
       :label="index" :value="index">
        <p class="title">{{ item.title }}</p>
        <p class="content">{{ item.content }}</p>
        <p class="info">
          <span class="info-item">{{ item.startDateTime.slice(0, 10) }}</span>
          <span v-if="item.planDateDesc" class="info-item">
            <svg-icon iconClass="clock" size="16"></svg-icon>
            <i>{{ item.planDateDesc }}计划</i>
          </span>
          <span v-if="item.remindDesc" class="info-item">
            <svg-icon iconClass="reminder" size="16"></svg-icon>
            <i>{{ item.remindDesc }}提醒</i>
          </span>
          <span v-if="item.repeatDesc" class="info-item">
            <svg-icon iconClass="repeat" size="16"></svg-icon>
            <i>{{ item.repeatDesc }}重复</i>
          </span>
        </p>
      </el-checkbox>
  </el-checkbox-group>
  <div class="result-footer" v-if="isTodoApp">
    <el-button type="info" @click="resendMessage">重新生成</el-button>
    <el-button type="success" :disabled="!checkList.length" @click="onSaveTodo">创建AI待办</el-button>
  </div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import agTable from '@/db/agTable'
import { parseTime, getUuid } from '@/utils'
export default {
  name: 'TodoList',
  inject: ['stopMessage', 'resendMessage', 'reEditMessage'], // 接收方法
  props: {
    item: Object,
    groupValue: String
  },
  data () {
    return {
      checkList: [],
      todos: []
    }
  },
  computed: {
    ...mapGetters(['chatStore', 'appInfo']),
    isTodoApp () {
      return this.appInfo.appID === 111
    },
    isChatDocument () { return this.chatStore.docSummarize.status !== '' }
  },
  created () {
    this.parseTodo()
  },
  methods: {
    replaceMsg () {

    },
    async onSaveTodo () {
      if (this.onAddTodo) return
      this.onAddTodo = true
      const todoList = []
      for (const item of this.checkList) {
        const data = this.getTodoItem(item)
        todoList.push(data)
      }
      if (!todoList.length) return
      this.$xz('HtmlClickReport', { ReportID: 7806 })
      await agTable.add(todoList)
      this.onAddTodo = false
      this.checkList = []
    },
    getTodoItem (index) {
      const todoItem = this.todos[index] || {}
      const config = {
        masterId: getUuid(),
        groupId: this.groupValue
      }
      return Object.assign(todoItem, config)
    },
    parseTodo () {
      let data = []
      const todoList = []
      let todoStr = ''
      try {
        const target = this.item.target
        todoStr = target.content.replace(/```json|```/g, '')
        const obj = JSON.parse(todoStr)
        data = obj.todos || []
      } catch (e) {
        data = []
      }
      for (const obj of data) {
        if (!obj.timePeriod?.startTime) break
        const todoItem = {
          title: obj.title,
          content: obj.content,
          startDateTime: obj.timePeriod.startTime,
          isTimeSelected: 1
        }
        const repetConfig = this.getRepetConfig(obj)
        const reminder = this.getReminderConfig(obj)
        if (obj.timePeriod.endTime) {
          todoItem.endDateTime = obj.timePeriod.endTime
        }
        if (reminder.length) {
          todoItem.reminders = reminder
          todoItem.remindDesc = this.getRemindDesc(todoItem)
        }
        todoItem.planDateDesc = this.getPlanDateDesc(todoItem)
        todoList.push(Object.assign(todoItem, repetConfig))
      }
      if (!todoList.length) {
        this.item.status = 'error'
        return
      }
      this.todos = todoList
      this.checkList = todoList.map((it, index) => index)
    },
    // eslint-disable-next-line sonarjs/cognitive-complexity
    getRepetConfig (data) {
      const repetConfig = {}
      const repetition = data.repetition || {}
      let daysOfMonth
      switch (repetition.type) {
        case 'DAYS':
          // todoItem.interval = repetition.interval || 1
          repetConfig.recurrenceFrequency = 1
          break
        case 'WEEKS_WEEKDAYS':
          const daysOfWeek = repetition.daysOfWeek || []
          if (daysOfWeek.length) {
            repetConfig.recurrenceFrequency = 2
            repetConfig.daysOfWeek = daysOfWeek.slice().map(w => w === 7 ? 0 : w).sort((a, b) => a - b)
          }
          break
        case 'WEEKS_WORKDAYS':
          repetConfig.recurrenceFrequency = 2
          repetConfig.daysOfWeek = [1, 2, 3, 4, 5]
          break
        case 'MONTHS_DAYS':
          daysOfMonth = repetition.daysOfMonth || []
          if (daysOfMonth.length) {
            repetConfig.recurrenceFrequency = 3
            repetConfig.dayOfMonth = [daysOfMonth[0]]
          }
          break
        case 'YEARS_MONTHS_DAYS':
          const monthsOfYear = repetition.monthsOfYear || []
          daysOfMonth = repetition.daysOfMonth || []
          if (monthsOfYear.length && daysOfMonth.length) {
            repetConfig.recurrenceFrequency = 4
            repetConfig.monthOfYear = monthsOfYear[0]
            repetConfig.dayOfMonth = [daysOfMonth[0]]
          }
          break
        case 'WORKING_DAYS':
          repetConfig.recurrenceFrequency = 1
          repetConfig.recurrenceOptionType = 8
          break
      }
      if (repetConfig.recurrenceFrequency) {
        repetConfig.interval = repetition.interval || 1
        repetConfig.cursorDate = data.timePeriod.startTime.slice(0, 10)
        if (!repetConfig.recurrenceOptionType) {
          repetConfig.recurrenceOptionType = -1
        }
        repetConfig.repeatDesc = this.getRepeatDesc(repetConfig)
      }
      return repetConfig
    },
    getRepeatDesc (data) {
      let desc = ''
      const toZhWeek = '日一二三四五六'
      const date = new Date(data.startDateTime)
      switch (data.recurrenceOptionType) {
        case 1:
          desc = '每天'
          break
        case 2:
          desc = '每周工作日'
          break
        case 3:
          desc = `每周（周${toZhWeek.charAt(date.getDay())}）`
          break
        case 4:
          desc = `每月（${date.getDate()}日）`
          break
        case 5:
          desc = `每月（第${data.weekOfMonth}个周${toZhWeek.charAt(date.getDay())}）`
          break
        case 6:
          desc = `每年（${date.getMonth() + 1}月${date.getDate()}日）`
          break
          // case 7:
          //   const lunar = Lunar.fromDate(date)
          //   desc = `每年（农历${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}）`
          //   break
        case 8:
          desc = '法定工作日'
          break
        case -1:
          desc = this.getCustomRepeatDesc(data)
      }
      return desc
    },
    getCustomRepeatDesc (data) {
      let desc = ''
      const {
        interval,
        recurrenceFrequency,
        daysOfWeek,
        dayOfMonth,
        monthOfYear,
        lastDay
      } = data
      const customType = ['', '天', '周', '月', '年']
      desc = `每${interval}${customType[recurrenceFrequency]}${
        recurrenceFrequency === 1 ? '' : '的'
      }`
      switch (recurrenceFrequency) {
        case 2:
          const toZhWeek = '日一二三四五六'
          desc += `${(daysOfWeek || [])
            .map(value => '周' + toZhWeek.charAt(value))
            .join('，')}`
          break
        case 3:
          const daysOfMonth = dayOfMonth || []
          if (lastDay === 1) {}
          daysOfMonth.length && (desc += `${daysOfMonth.join('，')}日`)
          if (lastDay === 1) {
            desc += `${daysOfMonth.length ? ',' : ''}${'最后一天'}`
          }
          break
        case 4:
          desc += `${monthOfYear}月${lastDay === 1 ? '最后一天' : dayOfMonth[0] + '日'}`
          break
      }
      return desc
    },
    getReminderConfig (data) {
      const reminder = []
      const list = data.advance_reminder || []
      list.forEach(item => {
        switch (item.unit) {
          case 'MINUTES':
            reminder.push(-item.time)
            break
          case 'HOURS':
            reminder.push(-item.time * 60)
            break
          case 'DAYS':
            reminder.push(-item.time * 60 * 24)
            break
          case 'WEEKS':
            reminder.push(-item.time * 60 * 24 * 7)
            break
        }
      })
      return reminder
      // advance_reminder
    },
    getRemindDesc (data) {
      const stamp = this.getRemindReferDate(data).getTime()
      return (data.reminders || [])
        .map(min => this.getDateWord(stamp, stamp + min * 60 * 1000))
        .join('，')
    },
    getRemindReferDate (data) {
      const d = new Date(data.startDateTime)
      d.setMilliseconds(0)
      d.setSeconds(0)
      // 未设置计划时间点，以9点为基准
      // !isTimeSelected && d.setHours(9, 0, 0, 0)
      return d
    },
    getDateWord (baseDate, date, flag = false) {
      baseDate = new Date(baseDate)
      date = new Date(date)
      const time = parseTime(date, '{h}:{i}')
      const days = (new Date(date).setHours(0, 0, 0, 0) -
       new Date(baseDate).setHours(0, 0, 0, 0)) /
      (1000 * 60 * 60 * 24)
      const weeks = days / 7
      let word = ''
      if (Number.isInteger(weeks) && weeks) {
        word = `${weeks < 0 ? '提前' : '延后'}${Math.abs(weeks)}周（${time}）`
      } else if (days) {
        word = `${days < 0 ? '提前' : '延后'}${Math.abs(days)}天`
        if (!(flag && days === 1 && parseTime(baseDate, '{h}:{i}') === time)) {
          word += `（${time}）`
        }
      } else {
        word = '当天（'
        const keyMap = {
          0: '准时',
          5: '提前5分钟',
          30: '提前30分钟',
          60: '提前1小时'
        }
        const minDiff = Math.abs(date.getMinutes() - baseDate.getMinutes())
        const w = keyMap[minDiff]
        if (flag && w) {
          word += w
        } else {
          word += `${time}`
        }
        word += '）'
      }
      return word
    },
    getPlanDateDesc (data, space = '-') {
      const { isTimeSelected, startDateTime, endDateTime } = data
      const desc = []
      if (isTimeSelected === 1) {
        desc.push(parseTime(startDateTime, '{h}:{i}'))
        if (endDateTime) {
          const end = parseTime(endDateTime, '{h}:{i}')
          !desc.includes(end) && desc.push(end)
        }
      }
      return desc.join(space)
    }
  }
}
</script>
<style lang="scss" scoped>
.result-footer{
  margin-top: 12px;
  text-align: center;
  .el-button{
    width: calc(50% - 8px);
    max-width: 200px;
  }
}
</style>
<style lang="scss">
$--primary-color:#0CC18A;
.todo-checkbox{
  position: relative;
  overflow-y: auto;
  margin-top: 5px;
  margin-right: -15px;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-right: 15px;
  .el-checkbox-group{
    display: block;
  }

  .el-checkbox{
    display: flex;
    align-items: center;
    margin-right: 0;
    &+.el-checkbox{
      margin-top: 10px;
    }
    &:hover,&.is-checked{
      .el-checkbox__label,.el-checkbox__input .el-checkbox__inner{
        border-color: $--primary-color;
      }
    }
    .el-checkbox__inner::after{
      border-color: #0CC18A;
    }
  }
  .el-checkbox__input{
    margin-right: 10px;
  }
  .el-checkbox__label{
    flex: 1;
    overflow: hidden;
    padding: 15px;
    background: rgba(255,255,255,0.05);
    box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.1);
    border-radius: 10px;
    border: 1px solid transparent;
    color: #fff!important;
  }
  .title{
    font-weight: bold;
    font-size: 16px;
  }
  .content{
    margin-top: 2px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-size: 12px;
  }
  .info{
    margin-top: 6px;
    font-size: 12px;
    white-space: break-spaces;
  }
  .info-item{
    &+.info-item{
      margin-left: 10px;
    }
    .svg-icon{
      margin-right: 4px;
    }
    i{
      font-style: normal;
    }
  }
}
</style>
